package com.lagou.homework.zookeeper;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONWriter;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

/**
 * @author shiyuhou
 * @version 1.0
 * @description: TODO
 * @date 6/22/21 5:56 PM
 */
public class ZkConfigLinster {


    static ZkClient zkClient = null;
    static DruidDataSource dataSource =null ;

    /**
     * @description: 连接zk,初始化mysql连接，监听指定目录，动态替换数据源
     * @return: void
     * @author shiyuhou
     * @date: 6/27/21 12:12 AM
     */
    public static void connectZK() throws SQLException {

        //创建zk客户端
        zkClient = new ZkClient("localhost:2181");
        if(!zkClient.exists("/mysql/localhost")){
            zkClient.createPersistent("/mysql/localhost",true);
        }
        //获取数据源相关信息
        Properties properties = CustomDruidDataSource.initProperties();
        dataSource = CustomDruidDataSource.getDataSource(properties);
        DruidPooledConnection connection = dataSource.getConnection();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("select now()");
        System.out.println(resultSet.next()?"连接初始化成功！"+resultSet.getString(1):"连接初始化成功！");
        //创建临时顺序节点，保存数据源相关信息
        JSONObject json=new JSONObject();
        json.put("url",dataSource.getUrl());
        json.put("username",dataSource.getUsername());
        json.put("password",dataSource.getPassword());
        zkClient.writeData("/mysql/localhost",json.toJSONString());
        System.out.println("---->>> 连接注册成功， 节点信息："+json.toJSONString());

    }

    public static void listenZK(){
        //zk监听保存目录，若监听到更改通知，则释放旧连接，创建新的连接
        zkClient.subscribeDataChanges("/mysql/localhost", new IZkDataListener() {

            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {

                JSONObject changeJson = JSONObject.parseObject(data.toString());
                System.out.println("dataPath = "+ dataPath +" data = "+data.toString());

                dataSource.close();

                CustomDruidDataSource.url=changeJson.getString("url");
                CustomDruidDataSource.username=changeJson.getString("username");
                CustomDruidDataSource.password=changeJson.getString("password");
                Properties properties1 = CustomDruidDataSource.initProperties();
                dataSource = CustomDruidDataSource.getDataSource(properties1);
                DruidPooledConnection connection1 = dataSource.getConnection();
                Statement statement1 = connection1.createStatement();
                ResultSet resultSet1 = statement1.executeQuery("select now()");
                System.out.println(resultSet1.next()?"新连接初始化成功！"+resultSet1.getString(1):"新连接初始化成功！");
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {

            }
        });
    }

    public static void main(String[] args) throws SQLException, InterruptedException {
        connectZK();
        while (true){
            Thread.sleep(2000L);
            listenZK();
        }
    }

}



